package com.yunquan.ohana.ui.weather

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.google.gson.Gson
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.ui.BaseActivity
import com.yunquan.ohana.databinding.ActivityWeatherBinding
import com.yunquan.ohana.entity.Location
import com.yunquan.ohana.utils.L
import com.yunquan.ohana.utils.LocationHelper
import com.yunquan.ohana.utils.StringUtils
import com.yunquan.ohana.utils.ToastUtils
import java.util.Locale

class WeatherActivity : BaseActivity<ActivityWeatherBinding, WeatherViewModel>(), LocationHelper.LocationResultListener {

    private var locationHelper: LocationHelper? = null

    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_weather
    }

    override fun initVariableId(): Int {
        return BR.weatherViewModel
    }

    override fun initParam() {
        super.initParam()
        Locale.setDefault(Locale("en"))
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            WindowCompat.setDecorFitsSystemWindows(window, false)
            window.statusBarColor = Color.TRANSPARENT
        } else {
            window.apply {
                decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                statusBarColor = Color.TRANSPARENT
            }
        }
    }

    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)
        locationHelper = LocationHelper(this)

        ViewCompat.setOnApplyWindowInsetsListener(binding!!.toolbar) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(0, systemBars.top, 0, 0)
            insets
        }

        val permissions = arrayOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )
        requestPermissions(permissions, 1001)
    }

    override fun onDestroy() {
        super.onDestroy()
        locationHelper?.destroy()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1001) {
            val isAllPass = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
            if (isAllPass) {
                // 全部通过, 开始执行定位操作
                showLoading()
                locationHelper?.getSingleLocation(this)
            } else {
                // 权限被拒绝
                ToastUtils.showShort(R.string.permission_denied)
            }
        }
    }

    override fun onLocationSuccess(latitude: Double, longitude: Double, cityName: String?) {
        L.d("定位成功：latitude = $latitude, longitude = $longitude, cityName = $cityName")
        // 定位成功，再获取系统语言
        viewModel!!.city.set(cityName)
        val lang = Locale.getDefault().language
        val location = "${longitude},${latitude}"
        viewModel!!.getWeatherData(location, lang)
    }

    override fun onLocationFailed(errorMessage: String) {
        dismissLoading()
        L.d("定位失败：$errorMessage")
        ToastUtils.showShort(R.string.location_failed)
    }

    override fun onActivityResult(result: ActivityResult) {
        super.onActivityResult(result)
        if (result.resultCode == RESULT_OK) {
            val dataJson = result.data?.getStringExtra("city")
            if (!StringUtils.isEmpty((dataJson))) {
                val cityBean = Gson().fromJson(dataJson, Location::class.java)
                if (cityBean != null) {
                    showLoading()
                    viewModel!!.city.set(cityBean.name)
                    val lang = Locale.getDefault().language
                    val location = "${cityBean.lon},${cityBean.lat}"
                    viewModel!!.getWeatherData(location, lang)
                }
            }
        }
    }
}